package com.zzyl.nursing.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONString;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;

import com.huaweicloud.sdk.core.utils.StringUtils;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceShadowVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;

/**
 * nursingService业务层处理
 * 
 * @author lapalace
 * @date 2025-08-03
 */
@Slf4j
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private IoTDAClient ioTDAClient;

    /**
     * 注册设备
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //防止重复，禁止数量大于等于1
        //1)设备名称
        //这里记住，Device这种domain会被用作数据库字段
        Long deviceNameCount = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery()
                .eq(Device::getDeviceName,deviceDto.getDeviceName()));
        if (deviceNameCount>=1){
            throw new BaseException("当前设备已存在！");
        }
        //2)设备唯一标识
        Long nodeCount = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery()
                .eq(Device::getNodeId, deviceDto.getNodeId()));
        if (nodeCount>=1){
            throw new BaseException("当前设备已存在！");
        }

        //3)同一位置的相同产品
        Long sameCount = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(deviceDto.getBindingLocation()),Device::getBindingLocation,deviceDto.getBindingLocation())
                .eq(ObjectUtil.isNotEmpty(deviceDto.getLocationType()),Device::getLocationType,deviceDto.getLocationType())
                .eq(ObjectUtil.isNotEmpty(deviceDto.getPhysicalLocationType()),Device::getPhysicalLocationType,deviceDto.getPhysicalLocationType())
                .eq(ObjectUtil.isNotEmpty(deviceDto.getProductKey()),Device::getProductKey,deviceDto.getProductKey()));
        if(sameCount>=1){
            throw new BaseException("当前位置已存在相同设备！");
        }

        //4)调用华为云IOT平台注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();

        AuthInfo authInfoBody = new AuthInfo();
        authInfoBody
                .withSecret(UUID.randomUUID().toString().replace("-",""));
        body.withAuthInfo(authInfoBody);
        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        body.setNodeId(deviceDto.getNodeId());
        request.withBody(body);

        //5)调用华为云
        AddDeviceResponse response = ioTDAClient.addDevice(request);
        String deviceId = response.getDeviceId();

        //6)将数据写入到本地 dto -> Device
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(deviceId);
        device.setSecret(authInfoBody.getSecret());
//        BeanUtil.copyProperties();
        save(device);
    }

    /**
     * 查询设备详情
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId,iotId));
        if (ObjectUtil.isEmpty(device)){
            return null;
        }

        //创建ShowDeviceRequest对象
        //ShowDeviceRequest用于构建查询设备详情的请求参数
        ShowDeviceRequest request = new ShowDeviceRequest();
        //设置要查询的设备ID
        request.setDeviceId(iotId);
        //ShowDeviceResponse用于封装从华为云IoTDA平台返回的设备详情信息
        ShowDeviceResponse response;
        try {
            //调用ioTDAClient.showDevice(request)发送请求
            //接收并处理ShowDeviceResponse响应
            response = ioTDAClient.showDevice(request);
        } catch (Exception e) {
            log.info("物联网接口 - 查询设备详情，调用失败:{}",e.getMessage());
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }

        //属性拷贝,处理激活时间，格式以及时区
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if(!StringUtils.isEmpty(activeTimeStr)){
            //UTC_MS_PATTERN   yyyy-MM-dd HH:mm:ss.SSS
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(activeTime);
        }
        return deviceDetailVo;
    }

    /**
     * 查询设备上报数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<DeviceShadowVo> queryServiceProperties(String iotId) {
        //1、调用华为云IOT，查询设备影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = ioTDAClient.showDeviceShadow(request);

        //2、查询不到，返回空
        List<DeviceShadowData> shadow = response.getShadow();
        if(CollUtil.isEmpty(shadow)){
            return Collections.emptyList();
        }

        //3、转换成Vo数据
        //3.1 获取属性集合信息
        JSONObject  jsonObject =JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //3.2 日期时区转换
        LocalDateTime eventTimeInfo = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        // 3.3 Vo封装
        List<DeviceShadowVo> vos = new ArrayList<>();
        jsonObject.forEach((key, value) -> {
            DeviceShadowVo vo = DeviceShadowVo.builder()
                    .functionId(key)
                    .value(value)
                    .eventTime(eventTimeInfo)
                    .build();
            vos.add(vo);
        });
        return vos;
    }

    /**
     * 查询所有产品
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if(StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }

        return JSONUtil.toList(jsonStr,ProductVo.class);
    }

    @Override
    public Device selectDeviceById(Long id) {
        return null;
    }

    @Override
    public List<Device> selectDeviceList(Device device) {
        return List.of();
    }

    @Override
    public int insertDevice(Device device) {
        return 0;
    }

    @Override
    public int updateDevice(Device device) {
        return 0;
    }

    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return 0;
    }

    @Override
    public int deleteDeviceById(Long id) {
        return 0;
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //通信
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = ioTDAClient.listProducts(request);
        if(response.getHttpStatusCode()!=200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //存入redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }
}
